/** 深度移除 null 和 '' */
import { isObject } from '@vueuse/core'

export function removeEmptyValue(obj) {
  if (obj) {
    return Object.entries(obj)?.reduce((pre, cur) => {
      const [key, value] = cur
      if (value !== null && value !== '') {
        if (isObject(value))
          pre[key] = removeEmptyValue(value)
        else
          pre[key] = value
      }
      return pre
    }, {})
  }
  return {}
}

/** 获取对象第一个键的值 */
export function firstItem(obj) {
  return Object.entries(obj)?.[0]?.[1]
}

export class QueryObject {
  public conditions: any[]
  public limit: number
  public start: number
  public count: boolean
  public sortBy: string
  public sortDirection: 'asc' | 'desc'
  public fields: string[]
  public replyWithCount: boolean
  public noError: boolean
  public groupBy?: string
  public queryCustomer?: boolean
  constructor(start = 0, limit = 20) {
    this.conditions = []
    this.limit = limit
    this.start = start
    this.count = false
    this.sortBy = 'createDate'
    this.sortDirection = 'desc'
    this.fields = []
    this.replyWithCount = true
    this.queryCustomer = true
    this.noError = false
  }
}
export function fnName(msg: string) {
  const arr = msg.split('.')
  const str = arr[arr.length - 1].replace('API', '').replace(/Msg.*/, '')
  return str
}
export function createAPIFn(httpInstance: any, msg: string) {
  return httpInstance.request.bind(httpInstance, msg)
}

export function getModuleMsgs(modules) {
  return Object.values(modules).flat() as string[]
}

interface MergeOption {
  extraKey?: string
  mainKey?: string
  targetKey?: string
}
/**
 * 合并两个列表
 * @param mainList 主列表
 * @param extraList 额外信息列表
 * @param option 合并配置
 * @param option.mainKey 主列表的唯一标识
 * @param option.extraKey 额外信息列表中与主列表对应的唯一标识
 * @param option.targetKey 取出的额外信息放入主列表的字段名
 */
export function mergeArrays(
  mainList,
  extraList,
  option: MergeOption = {},
) {
  const { extraKey = 'uuid', mainKey = 'accountUuid', targetKey = 'account' } = option
  const extraMap = new Map()
  if (!mainList.length || !extraList.length)
    return mainList || []
  extraList.forEach(item => extraMap.set(item[extraKey], item)) // 把要追加的列表转为唯一标识映射
  return mainList.reduce((acc, cur) => {
    const mkey = cur[mainKey]
    if (extraMap.has(mkey))
      acc.push({ ...cur, [targetKey]: extraMap.get(mkey) })
    else
      acc.push(cur)
    return acc
  }, [])
}

export function poll(instance, response) {
  function getUrl(response) {
    const { data: { uuid = '' }, config: { url = '' } } = response
    const suffix = uuid && !url.includes('/result') ? `/result/${uuid}` : ''
    return url + suffix
  }

  const path = getUrl(response)
  return new Promise((resolve) => {
    setTimeout(resolve, 1000)
  }).then(() => {
    return instance.get(path)
  })
}
